from flask import Flask, render_template
from flask_socketio import SocketIO, disconnect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)

@app.route('/')
def sessions():
    return render_template('test.html')

# listening: default event
@socketio.on('connect')
def connect_default_event():
    print('client: connect')
    socketio.send('client: connect')


# 服务连接后一直在print message
# @socketio.on('message')
# def message_default_event(message):
#     print(message)
#     socketio.send('client:' + message)

@socketio.on('json')
def json_default_event(json):
    print(json)
    socketio.send('client:' + str(json))

@socketio.on('disconnect')
def disconnect_default_event():
    print('client: disconnect')
    socketio.send('client: disconnect')

# listening: custom event

def messageReceived(methods=['GET', 'POST']):
    print('message was received!!!')

@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    print('received my event: ' + str(json))
    socketio.emit('my response', json, callback=messageReceived)
    print('json', json)
    if json['message'] == 'disconnect':
        # to disconnect connect
        disconnect()



if __name__ == '__main__':
    socketio.run(app, debug=True)